<!--
 * @Author: 小羊今晚不睡觉 2226764294@qq.com
 * @Date: 2025-10-09 10:20:37
 * @LastEditors: 小羊今晚不睡觉 2226764294@qq.com
 * @LastEditTime: 2025-10-09 13:30:46
 * @FilePath: \yougongxia-backstage\src\views\position\detail.vue
 * @Description: 二级工种管理页面
-->
<template>
    <!-- 查询表单 -->
    <n-card :bordered="false">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset" :showAdvancedButton="false" />
    </n-card>

    <!-- 二级工种列表 -->
    <n-card :bordered="false" class="mt-3">
        <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
            :action-column="actionColumn" :scroll-x="1090" :striped="true" :showSelection="true"
            @update:checked-row-keys="onCheckedRow">
            <template #tableTitle>
                <n-button type="primary" @click="openModal">
                    <template #icon>
                        <n-icon>
                            <PlusOutlined />
                        </n-icon>
                    </template>
                    新建具体工种
                </n-button>
                <n-button type="error" @click="batchDelete" :disabled="checkedRowKeys.length === 0" class="ml-2">
                    批量删除
                </n-button>
            </template>
        </BasicTable>
    </n-card>

    <!-- 新增/编辑表单弹窗 -->
    <n-modal v-model:show="showModal" :title="modalTitle" :show-icon="false" preset="dialog">
        <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="100" class="py-4">
            <n-form-item label="工种类别" path="parentId">
                <n-select placeholder="请选择工种类别" v-model:value="formParams.parentId" :options="firstLevelOptions" />
            </n-form-item>
            <n-form-item label="具体工种" path="name">
                <n-input placeholder="请输入具体工种" v-model:value="formParams.name" />
            </n-form-item>
            <n-form-item label="状态" path="isActive">
                <n-radio-group v-model:value="formParams.isActive">
                    <n-radio :value="true">启用</n-radio>
                    <n-radio :value="false">禁用</n-radio>
                </n-radio-group>
            </n-form-item>
        </n-form>
        <template #action>
            <n-space>
                <n-button @click="() => (showModal = false)">取消</n-button>
                <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
            </n-space>
        </template>
    </n-modal>
</template>

<script lang="ts" setup>
import { h, reactive, ref, onMounted } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { JobCategoryItem, JobCategoryOption } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { NTag, useMessage, useDialog } from 'naive-ui';
import { debounce } from 'lodash-es';

// API
import {
    getJobCategories,
    getFirstLevelCategories,
    addJobCategory,
    updateJobCategory,
    deleteJobCategories,
} from '@/api/position/index';

// --- Refs & Reactive ---
const message = useMessage();
const dialog = useDialog();

// Table
const actionRef = ref<any>(null);
const checkedRowKeys = ref<(string | number)[]>([]);

// Forms & Modals
const showModal = ref(false);
const isEdit = ref(false);
const modalTitle = ref('新建二级工种');
const formBtnLoading = ref(false);
const formRef: any = ref(null);

// 一级工种下拉选项
const firstLevelOptions = ref<JobCategoryOption[]>([]);

const searchParams = reactive({
    parentId: null as number | null,
    parentName: '', // 用于存储搜索时的一级工种名称
    name: '',
});

// Form params for add/edit
const formParams = reactive<Partial<JobCategoryItem>>({
    id: undefined,
    parentId: null,
    name: '',
    isActive: true,
});

// Form rules
const rules = {
    parentId: {
        required: true,
        message: '请选择工种类别',
    },
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入具体工种',
    },
    isActive: {
        required: true,
        message: '请选择状态',
    },
};

// --- Form Schema ---
const schemas: FormSchema[] = [
    {
        field: 'parentId',
        component: 'NSelect',
        label: '工种类别',
        componentProps: {
            placeholder: '请选择工种类别',
            options: firstLevelOptions,
            'onUpdate:value': (value: number | null) => {
                searchParams.parentId = value;
                if (value === null) {
                    searchParams.parentName = '';
                } else {
                    const selectedOption = firstLevelOptions.value.find(option => option.value === value);
                    searchParams.parentName = selectedOption ? selectedOption.label : '';
                }
            },
        },
    },
    {
        field: 'name',
        component: 'NInput',
        label: '具体工种',
        componentProps: {
            placeholder: '请输入具体工种',
            'onUpdate:value': (value: string) => {
                searchParams.name = value;
            },
        },
    },
];

const [register] = useForm({
    model: searchParams,
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 100,
    schemas,
    initialValues: {
        parentId: null,
        name: '',
    },
});

const handleCheckedRowChange = debounce((keys: (string | number)[]) => {
    checkedRowKeys.value = keys;
}, 50);

const onCheckedRow = (keys: (string | number)[]) => {
    handleCheckedRowChange(keys);
};

// --- 二级工种列表列定义 ---
const columns = [
    {
        title: '工种类别',
        key: 'parentName',
        align: 'center',
    },
    {
        title: '具体工种',
        key: 'name',
        align: 'center',
    },
    {
        title: '状态',
        align: 'center',
        key: 'isActive',
        render(record) {
            const status = record.isActive ? 'enable' : 'disable';
            const statusMap = { enable: '启用', disable: '禁用' };
            return h(
                NTag,
                {
                    type: status === 'enable' ? 'success' : 'error',
                },
                { default: () => statusMap[status] }
            );
        },
    }
];

// --- Methods ---
// 获取一级工种列表
const getFirstLevelList = async () => {
    try {
        const res = await getFirstLevelCategories();
        firstLevelOptions.value = (res.data || res).map((item: JobCategoryItem) => ({
            label: item.name,
            value: item.id
        }));
    } catch (error) {
        message.error('获取一级工种列表失败');
    }
};

const loadDataTable = async (params) => {
    const query = {
        parentName: searchParams.parentName,
        name: searchParams.name,
        ...params, // 分页参数
    };
    return await getJobCategories(query);
};

const reloadTable = () => {
    actionRef.value.reload();
};

const handleSubmit = () => {
    reloadTable();
};

const handleReset = () => {
    searchParams.parentId = null;
    searchParams.parentName = '';
    searchParams.name = '';
    reloadTable();
};

// 打开新增弹窗
const openModal = async () => {
    await getFirstLevelList();
    isEdit.value = false;
    modalTitle.value = '新建二级工种';
    formParams.id = undefined;
    formParams.parentId = null;
    formParams.name = '';
    formParams.isActive = true;
    showModal.value = true;
};

// --- Action Column Definition ---
const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    align: 'center',
    fixed: 'right',
    render(record: JobCategoryItem) {
        const actionTextMap = { enable: '启用', disable: '禁用' };
        return h(TableAction as any, {
            style: 'text',
            actions: [
                { label: '编辑', onClick: () => handleEdit(record) },
                { label: '删除', type: 'error', onClick: () => handleDelete(record) },
            ],
            dropDownActions: [
                { label: '启用', key: 'enable', ifShow: () => !record.isActive },
                { label: '禁用', key: 'disable', ifShow: () => record.isActive },
            ],
            select: (key: string) => {
                const newStatus = key === 'enable';
                const actionText = actionTextMap[key as keyof typeof actionTextMap];
                updateStatus(record, newStatus, actionText!);
            },
        });
    },
});

const updateStatus = async (record: JobCategoryItem, newStatus: boolean, actionText: string) => {
    try {
        const payload = {
            name: record.name,
            jobCategoryId: record.id,
            parentId: record.parentId,
            isActive: newStatus,
        };
        await updateJobCategory(payload);
        message.success(`${actionText}成功`);
        reloadTable();
    } catch (error) {
        message.error(`${actionText}失败，请稍后重试`);
    }
};

// 编辑
const handleEdit = async (record: JobCategoryItem) => {
    await getFirstLevelList();
    isEdit.value = true;
    modalTitle.value = '编辑二级工种';
    formParams.id = record.id;
    formParams.parentId = record.parentId;
    formParams.name = record.name;
    formParams.isActive = record.isActive;
    showModal.value = true;
};

// 删除单条
const handleDelete = async (record: JobCategoryItem) => {
    dialog.warning({
        title: '确认删除',
        content: `确定要删除二级工种【${record.name}】吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            await deleteJobCategories([record.id]);
            message.success('删除成功');
            reloadTable();
        },
    });
};

// 批量删除
const batchDelete = async () => {
    dialog.warning({
        title: '确认批量删除',
        content: `确定要删除选中的 ${checkedRowKeys.value.length} 条数据吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            await deleteJobCategories(checkedRowKeys.value as number[]);
            message.success('批量删除成功');
            checkedRowKeys.value = [];
            reloadTable();
        },
    });
};

// 提交表单
const confirmForm = async () => {
    formBtnLoading.value = true;
    try {
        await formRef.value.validate();

        const payload: any = {
            parentId: formParams.parentId, // 依然使用 parentId
            name: formParams.name,
            isActive: formParams.isActive,
        };

        if (isEdit.value) {
            payload.jobCategoryId = formParams.id;
            await updateJobCategory(payload);
            message.success('修改成功');
        } else {
            await addJobCategory(payload);
            message.success('新增成功');
        }

        showModal.value = false;
        reloadTable();

    } catch (error: any) {
        if (error !== 'Validate Failed') {
            message.error('操作失败，请稍后重试');
        }
    } finally {
        formBtnLoading.value = false;
    }
};

onMounted(() => {
    getFirstLevelList();
});
</script>